<template>
	<view class="apply-page">
		<view class="invoice-info">
			<view class="section-title">发票信息</view>
			<view class="info-content">
				<view class="info-item">
					<text class="label">发票内容</text>
					<text class="value">{{formData.invoiceContent}}</text>
				</view>
				<view class="info-item" @click="selectInvoiceTitle">
					<text class="label">发票抬头</text>
					<view class="value link">
						{{formData.invoiceTitle}}
						<u-icon name="arrow-right" size="24rpx" color="#777" bold></u-icon>
					</view>
				</view>
				<view class="info-item">
					<text class="label">纳税人识别号</text>
					<text class="value">{{formData.taxpayerNo}}</text>
				</view>
				<view class="info-item">
					<text class="label">开票金额</text>
					<text class="value amount">¥{{ isMultiOrder ? totalAmount.toFixed(2) : formData.amount }}</text>
				</view>
				<!-- <view class="info-item">
					<text class="label">注册地址</text>
					<input type="text" v-model="formData.regAddress" placeholder="请输入注册地址" />
				</view>
				<view class="info-item">
					<text class="label">注册电话</text>
					<input type="text" v-model="formData.regPhone" placeholder="请输入注册电话" />
				</view>
				<view class="info-item">
					<text class="label">开户银行</text>
					<input type="text" v-model="formData.bankName" placeholder="请输入开户银行" />
				</view>
				<view class="info-item">
					<text class="label">银行账号</text>
					<input type="text" v-model="formData.bankAccount" placeholder="请输入银行账号" />
				</view> -->
			</view>
		</view>
		
		<view class="email-info">
			<view class="section-title">发票信息</view>
			<view class="info-item flex flex-between">
				<text class="label" style="flex: 1;">邮箱号</text>
				<view class="value" style="flex: 2;">
					<input disabled="disabled" type="text" class="email-input" v-model="formData.email" placeholder="请输入接收发票的邮箱地址"/>
				</view>
			</view>
		</view>
		
		<button class="confirm-btn" @click="confirmApply">确认开票</button>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				formData: {
					orderId: 0,
					invoiceTitle: "",
					taxpayerNo: "",
					invoiceContent: "充电费",
					amount: 0,
					email: "",
					regAddress: "",
					regPhone: "",
					bankName: "",
					bankAccount: ""
				},
				isMultiOrder: false,
				totalAmount: 0,
				orderIds: ''
			}
		},
		onLoad({ id }) {
			if(id) {
				const ids = id.split(',').map(item => parseInt(item));
				this.isMultiOrder = ids.length > 1;
				
				if(this.isMultiOrder) {
					this.orderIds = ids;
				} else {
					this.formData.orderId = ids[0];
				}
			}
			this.getOrderAmount();
			this.getDefaultInvoiceInfo();
			uni.$on('invoiceSelect', data => this.setInvoiceData(data));
		},
		methods: {
			getDefaultInvoiceInfo() {
				this.$http_api.defaultInvoiceInfo({}).then(res => this.setInvoiceData(res))
			},
			
			getOrderAmount() {
				if(this.isMultiOrder) {
					const promises = this.orderIds.map(id => 
						this.$http_api.orderDetail({ id }).then(res => res.chargedAmount)
					);
					Promise.all(promises).then(amounts => {
						this.totalAmount = amounts.reduce((sum, amount) => sum + amount, 0);
					});
				} else {
					this.$http_api.orderDetail({ id: this.formData.orderId }).then((res) => {
						this.formData.amount = res.chargedAmount;
					})
				}
			},
			
			setInvoiceData(data) {
				const { 
					id, 
					invoiceTitle, 
					taxpayerNo, 
					email,
					regAddress,
					regPhone,
					bankName,
					bankAccount 
				} = data;
				
				Object.assign(this.formData, {
					invoiceTitle,
					taxpayerNo,
					email,
					regAddress,
					regPhone,
					bankName,
					bankAccount
				});
			},
			
			selectInvoiceTitle() {
				uni.navigateTo({
					url: '/pages/user/users/info/invoice?type=1'
				})
			},
			
			validateEmail(email) {
				const reg = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
				return reg.test(email)
			},

			validateForm() {
				const requiredFields = {
					invoiceTitle: '发票抬头',
					taxpayerNo: '纳税人识别号',
					email: '邮箱地址',
					regAddress: '注册地址',
					regPhone: '注册电话',
					bankName: '开户银行',
					bankAccount: '银行账号'
				};

				for (const [field, label] of Object.entries(requiredFields)) {
					if (!this.formData[field]) {
						uni.$u.toast(`请输入${label}`);
						return false;
					}
				}

				if (!this.validateEmail(this.formData.email)) {
					uni.$u.toast('请输入正确的邮箱格式');
					return false;
				}

				return true;
			},

			confirmApply() {
				if (!this.validateForm()) return;
				
				const createInvoice = (api, data) => {
					api(data).then(res => {
						uni.$u.toast('开票申请已提交');
						setTimeout(() => uni.redirectTo({
							url: '/pages/user/users/invoice/result'
						}), 1000);
					}).catch(err => {
						uni.$u.toast(err || '开票申请失败');
					});
				};

				if(this.isMultiOrder) {
					const requestData = this.orderIds.map(orderId => ({
						...this.formData,
						orderId,
						amount: this.totalAmount / this.orderIds.length
					}));
					createInvoice(this.$http_api.invoiceCreateList, requestData);
				} else {
					createInvoice(this.$http_api.invoiceCreate, this.formData);
				}
			}
		}
	}
</script>

<style scoped lang="scss">
	.apply-page {
		padding: 20rpx;
		
		.section-title {
			font-size: 32rpx;
			font-weight: bold;
			margin-bottom: 20rpx;
		}
		
		.invoice-info, .invoice-amount, .email-info {
			background: #fff;
			border-radius: 12rpx;
			padding: 20rpx;
			margin-bottom: 20rpx;
			
			.info-content {
				.info-item {
					display: flex;
					justify-content: space-between;
					align-items: center;
					padding: 20rpx 0;
					border-bottom: 1rpx solid #eee;
					
					&:last-child {
						border-bottom: none;
					}
					
					.label {
						color: #666;
						font-size: 28rpx;
					}
					
					.value {
						color: #333;
						font-size: 28rpx;
						font-family: "PINGFANG";
						
						&.link {
							color: #333;
							display: flex;
							align-items: center;
							
							.arrow {
								color: #999;
								margin-left: 10rpx;
							}
						}
						
						&.amount {
							color: #FC0A01;
							font-weight: 600;
						}
					}
					
					input {
						text-align: right;
						font-size: 28rpx;
						color: #333;
					}
				}
			}
		}
		
		.email-info {
			.label {
				color: #666;
				font-size: 28rpx;
			}
			.email-input {
				height: 80rpx;
				border-bottom: 1rpx solid #eee;
				padding: 0 20rpx;
				font-size: 28rpx;
			}
		}
		
		.confirm-btn {
			position: fixed;
			bottom: calc(40rpx + constant(safe-area-inset-bottom));
			bottom: calc(40rpx + env(safe-area-inset-bottom));
			left: 40rpx;
			right: 40rpx;
			background: #2979ff;
			color: #fff;
			height: 88rpx;
			line-height: 88rpx;
			border-radius: 44rpx;
			font-size: 32rpx;
		}
	}
</style>